'use strict';
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow



var sqlite3 = require('sqlite3').verbose();
const path = require('path');
var db = new sqlite3.Database(path.join(__dirname, 'db.db'));















// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600})

  // and load the index.html of the app.
  mainWindow.loadURL(`file://${__dirname}/index.html`)

  // Open the DevTools.
  mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

var ffi$1 = require("ffi");


//sdk方法定义
var libSunVoteSDK =  new ffi$1.Library("SunVoteSDK_x64.dll", {
  "License": [ "int", [ "int","string" ] ],
  "Connect":["int",["int","string"] ],
  "Disconnect":["int",["int"] ],
  "WriteHDParam":["int",["int","int","string"] ],
  "ReadHDParam":["int",["int","int"] ],
  "WriteKeypadParam":["int",["int","int","string","int","string"] ],
  "ReadKeypadParam":["int",["int","int","string","int","string"] ],
  "VoteStart2":["int",["int","int","string"] ],
  "VoteStop2":["int",["int"] ],
  "GetMultiResultByID":["int",["string","int","int"] ],
  "GetResultBySN":["int",["string","int","int"] ],
  "ExitGetResult":["int",[] ],
  "SetLogOn":["int",["int"]],
  "SetHDParamEventCallBack":["void",["pointer"] ],
  "SetKeypadParamEventCallBack":["void",["pointer"] ],
  "SetConnectEventCallBack":["void",["pointer"] ],
  "SetVoteEventCallBack":["void",["pointer"] ],
  "SetKeyEventCallBack":["void",["pointer"] ],
  
});



var paramEnum = {
  //连接方式
  conn_type_usb :1,
  conn_type_tcpip :2,

  // 基站设置	更多参数定义请参考 param_def.h文件，此处只列举部分 
  BaseStation_RFPower : 1,				//基站功率
  BaseStation_Channel : 2,				// ,  基站主信道
  BaseStation_CommunicationChannels : 3,	//通讯通道：是否中继，通道数，通道1，通道2，通道3，通道4
  BaseStation_IP : 4,						//IP
  BaseStation_MAC : 5,					//mac地址
  BaseStation_SubnetMask : 6,				//子网掩码
  BaseStation_Gateway : 7,				//网关
  BaseStation_Title : 8,					//基站名称
  BaseStation_ID : 9,						//基站编号
  BaseStation_SN : 10,						//硬件序列号（ 只读）
  BaseStation_Version : 11,				//硬件版本
  BaseStation_PairCode : 12,				//配对码
  BaseStation_MatchCode : 12,				//配对码
  SoftwareDongle_VerifyPWD : 13,			//验证密码
  SoftwareDongle_A_PWD : 14,				//软件狗密码
  SoftwareDongle_A_Zone : 15,				//软件狗读写A区
  SoftwareDongle_B_Zone : 16,
  KeyPad_config : 17,						//键盘设置  ReportMode, offtime, SubmisMode, Buzzer, LCD,Vib, Lang
  KeyPad_ConnectionMode : 18,				//键盘连接模式（固定配对、自由配对、免配对）
  Kaypad_WorkingMode : 18,				//键盘连接模式（固定配对、自由配对、免配对）
  KeyPad_IdentificationMode : 19,			//键盘识别模式（是否SN号模式）
  KeyPad_ID : 20,							//键盘编号
  KeyPad_UserID : 21,						//用户编号
  KeyPad_SN : 22,							//键盘出厂序列号
  KeyPad_Version : 23,					//键盘版本信息
  KeyPad_PairCode : 24,					//配对码
  Keypad_UserName : 35,					//用户姓名
  KeyPad_PowerOff : 222,
  WiFi_SSID : 25,							//组合 BaseMode,ssid
  WiFi_WorkMode : 26,
  WiFi_Password : 27,
  
  

  // 投票设置
  VoteType_Free : 0,						//空闲模式(停止)
  VoteType_Signin : 1,					//签到
  VoteType_Vote : 2,						//表决
  VoteType_Number : 4,					//数值 （单项评分模式）
  VoteType_TrueFalse : 5,					//判断
  VoteType_KeyPadTest : 9	,				//模拟测试
  VoteType_Choice : 10,					//选择
  VoteType_Sequence : 11,					//排序
  VoteType_FillBlanks : 12,				//填空
  VoteType_Quiz : 13,						//抢答
  VoteType_Examination : 14,				//测验
  VoteType_Homework : 15,					//作业
  VoteType_Election : 22,                 //选举
  VoteType_KeyPadPair : 40,				//配对
  VoteType_KeyPadMatch : 40,				//配对
  VoteType_continue : 100,
  VoteType_submitAndContinue : 101,

  // 键盘结果
  KeyResult_info : 1,						//结果
  KeyResult_status : 2,					//状态
  KeyResult_loginInfo : 3,				//配对（登录）信息
  KeyResult_remoteControlAnswer : 4,		// 表决器遥控指令应答

}

//var BrowserWindow = require('browser-window');
var ffi = require("ffi");
// Special module holding environment variables which you declared
// in config/env_xxx.json file.
var ipc = require("electron").ipcRenderer
const ipcMain = require('electron').ipcMain;
global.sharedObject = {
    loginuser: '',
    objson: {},
};

libSunVoteSDK.License(1, "SUNARS2013");
libSunVoteSDK.SetLogOn(2);

function connCallBack(iBaseID, iMode, sInfo) {
    console.log("ConnectEventCallBack--:"+"baseID :"+iBaseID +" BaseMode:"+ iMode + " sInfo:" +sInfo);
     if(sInfo == "1"){
       console.log("Connected....");
	   console.log("VoteStart2");
	   libSunVoteSDK.VoteStart2(0,40, "1,0");
	   
        // keyStr=35;//Keypad_UserName
		//var  Base_Version = 11;
		//console.log("WriteKeypadParam");
		///libSunVoteSDK.WriteKeypadParam(0,0xffff,"1234567890",keyStr,"Tom");
		
        //var  Base_Version = 11;
        //libSunVoteSDK.ReadHDParam(0,Base_Version);
        //var vote_type_choice = 10;
       // libSunVoteSDK.VoteStart(10,"1,1,0,0,4,1");
     }
}

function voteCallBack(iBaseID, iMode, sInfo) {
    console.log("voteCallBack--:"+"baseID :"+iBaseID +" BaseMode:"+ iMode + " sInfo:" +sInfo);
}

function keyCallBack(BaseID,KeyID,KeySN,iMode,Time,sInfo) {
  console.log("keyCallBack--: BaseID:"+BaseID+" KeyID :"+KeyID +"KeySN"+KeySN+ " BaseMode:"+ iMode +" Time:"+Time +" sInfo:" +sInfo);
}

 
function hdParamCallBack(iBaseID, iMode, sInfo) {
  console.log("HDParamEventCallBack--:"+"baseID :"+iBaseID +" BaseMode:"+ iMode + " sInfo:" +sInfo);
}

function keypadParamCallBack(iBaseID,iKeyid,sKeySn, iMode, sInfo) {
  console.log("KeypadParamCallBack--:"+"baseID :"+iBaseID +" BaseMode:"+ iMode + " sInfo:" +sInfo);
}

var ConnectEventCallBack = ffi.Callback('void', ['int', 'int', 'string'], connCallBack);
var VoteEventCallBack = ffi.Callback('void', ['int', 'int', 'string'], voteCallBack);
var KeyEventCallBack = ffi.Callback('void', ['int','int','string', 'int', 'float','string'], keyCallBack);
var HDParamEventCallBack = ffi.Callback('void',['int','int','string'],hdParamCallBack);
var KeypadParamEventCallBack = ffi.Callback('void',['int','int','string', 'int','string'],keypadParamCallBack);



libSunVoteSDK.SetConnectEventCallBack(ConnectEventCallBack);
libSunVoteSDK.SetHDParamEventCallBack(HDParamEventCallBack);
libSunVoteSDK.SetKeypadParamEventCallBack(KeypadParamEventCallBack);
libSunVoteSDK.SetKeyEventCallBack(KeyEventCallBack);
libSunVoteSDK.SetVoteEventCallBack(VoteEventCallBack);

libSunVoteSDK.Connect(paramEnum.conn_type_usb, "");

/* function test(){
  var keyStr = 1;
  for(var i=0;i<100;i++){
    console.log(keyStr);
    libSunVoteSDK.VoteStart(keyStr, "1,1,0,0,4,1");
    if(i%2 == 0){
      keyStr=10
    }else{
      keyStr = 1;
    }

  }
} */

var i = 1;
var keyStr = paramEnum.VoteType_Choice;//10;
function test2(){
  
   if(i%2 == 0){
    keyStr=35;//Keypad_UserName
    var  Base_Version = 11;
	console.log("WriteKeypadParam");
    libSunVoteSDK.WriteKeypadParam(0,0xff,"1234567890",keyStr,"Tom");
  }else{
   /* keyStr = 10;
	
	console.log("startVote");
	console.log('i='+i+",type="+keyStr);
	libSunVoteSDK.VoteStart2(0,keyStr, "1,1,0,0,4,1");*/
  } 
  
 
 
  i++;
  
  if(i<2){
    setTimeout(test2,'5000');
  }
}
//test2();
